package com.lex.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lex.common.api.CommonResult;
import com.lex.data.admin.mapper.LexSysDictDataMapper;
import com.lex.data.admin.mapper.LexSysDictTypeMapper;
import com.lex.data.admin.model.LexSysDictData;
import com.lex.data.admin.model.LexSysDictType;
import com.lex.entity.params.DictDataQueryParams;
import com.lex.entity.params.DictDataStatusQuery;
import com.lex.entity.params.DictTypeQueryParams;
import com.lex.entity.params.DictTypeStatusQuery;
import com.lex.service.DictService;
import com.lex.util.MyContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.stylesheets.LinkStyle;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
@Slf4j
@Service
public class DictServiceImpl implements DictService {

    @Autowired
    private LexSysDictTypeMapper lexSysDictTypeMapper;

    @Autowired
    private LexSysDictDataMapper lexSysDictDataMapper;

    /**
     * 更新数据字典类型状态
     * @param dictTypeStatusQuery
     *
     * @return
     */
    @Override
    public CommonResult updateTypeStatus(DictTypeStatusQuery dictTypeStatusQuery) {
        LexSysDictType lexSysDictType = lexSysDictTypeMapper.selectOne(
                new QueryWrapper<LexSysDictType>()
                        .eq("dict_id", dictTypeStatusQuery.getDict_id()));
        if (lexSysDictType == null) {
            return CommonResult.failed("字典类型不存在！");
        }
        lexSysDictType.setStatus(dictTypeStatusQuery.getStatus());
        int result = lexSysDictTypeMapper.update(
                lexSysDictType,
                new QueryWrapper<LexSysDictType>()
                        .eq("dict_id", dictTypeStatusQuery.getDict_id()));
        return result > 0 ? CommonResult.success("更新数据成功！") : CommonResult.failed("更新数据失败！");
    }

    /**
     * 新增字典类型
     * @param dictType
     * @return
     */
    @Override
    public CommonResult createType(LexSysDictType dictType) {
        //dictType不能重复
        LexSysDictType lexSysDictType = lexSysDictTypeMapper.selectOne(
                new QueryWrapper<LexSysDictType>()
                        .eq("dict_type", dictType.getDictType()));
        if (lexSysDictType != null) {
            return CommonResult.failed("字典类型已存在！");
        }
        String creatBy = MyContext.getCurrentUserName();
        dictType.setCreateBy(creatBy);
        long now_time = System.currentTimeMillis();
        Timestamp timestamp = new Timestamp(now_time);
        dictType.setCreateTime(timestamp);
        int result = lexSysDictTypeMapper.insert(dictType);
        return result > 0 ? CommonResult.success("新增数据成功！") : CommonResult.failed("新增数据失败！");
    }

    /**
     * 修改字典类型
     *
     * @param dictType
     * @return
     */
    @Override
    @Transactional
    public CommonResult updateType(LexSysDictType dictType) {
        String update_by = MyContext.getCurrentUserName();
        //查询字典类型
        LexSysDictType lexSysDictType = lexSysDictTypeMapper.selectOne(
                new QueryWrapper<LexSysDictType>()
                        .eq("dict_id", dictType.getDictId()));
        if (lexSysDictType == null) {
            return CommonResult.failed("字典类型不存在！");
        }
        //dictType不能重复
        if(!lexSysDictType.getDictType().equals(dictType.getDictType())){
            LexSysDictType lexSysDictType1 = lexSysDictTypeMapper.selectOne(
                    new QueryWrapper<LexSysDictType>()
                            .eq("dict_type", dictType.getDictType()));
            if (lexSysDictType1 != null) {
                return CommonResult.failed("字典类型已存在！");
            }
            //如果和原来的不一样，就更新字典数据的type
            LexSysDictData newDictData = new LexSysDictData();
            newDictData.setDictType(dictType.getDictType());
            lexSysDictDataMapper.update(
                    newDictData,
                    new QueryWrapper<LexSysDictData>()
                            .eq("dict_type", lexSysDictType.getDictType()));
        }

        dictType.setUpdateBy(update_by);
        long now_time = System.currentTimeMillis();
        Timestamp timestamp = new Timestamp(now_time);
        dictType.setUpdateTime(timestamp);
        int result = lexSysDictTypeMapper.update(
                dictType,
                new QueryWrapper<LexSysDictType>()
                        .eq("dict_id", dictType.getDictId()));

        return result > 0 ? CommonResult.success("修改数据成功！") : CommonResult.failed("修改数据失败！");
    }

    /**
     * 删除字典类型
     * @param dict_id
     * @return
     */
    @Override
    @Transactional
    public CommonResult deleteType(Long dict_id) {
        //查询字典类型
        LexSysDictType lexSysDictType = lexSysDictTypeMapper.selectOne(
                new QueryWrapper<LexSysDictType>()
                        .eq("dict_id", dict_id));
        if (lexSysDictType == null) {
            return CommonResult.failed("字典类型不存在！");
        }
        //删除字典类型
        int result = lexSysDictTypeMapper
                .delete(new QueryWrapper<LexSysDictType>().eq("dict_id", dict_id));
        //删除字典数据
        lexSysDictDataMapper.delete(new QueryWrapper<LexSysDictData>().eq("dict_type", lexSysDictType.getDictType()));
        return result > 0 ? CommonResult.success("删除数据成功！") : CommonResult.failed("删除数据失败！");
    }

    /**
     * 获取所有字典类型列表
     * @param  query, Integer pageSize, Integer page
     * @return
     */
    @Override
    public CommonResult allDictListType(DictTypeQueryParams query, Integer pageSize, Integer page) {
        Page<LexSysDictType> lexSysDictTypePage = new Page<>(page, pageSize);
        QueryWrapper<LexSysDictType> queryWrapper = new QueryWrapper<>();
        if ( query.getDictName() != null) {
            queryWrapper.like("dict_name", query.getDictName());
        }
        if (query.getDictType() != null) {
            queryWrapper.like("dict_type", query.getDictType());
        }
        if (query.getStatus() != null) {
            queryWrapper.eq("status", query.getStatus());
        }
        List<LexSysDictType> lexSysDictTypeList = lexSysDictTypeMapper.selectList(lexSysDictTypePage, queryWrapper);
        long total = lexSysDictTypePage.getTotal();
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("items", lexSysDictTypeList);
        return CommonResult.success(map);
    }

    /**
     * 获取所有字典数据列表
     * @param query
     * @param pageSize
     * @param page
     * @return
     */
    @Override
    public CommonResult allDictListData(DictDataQueryParams query, Integer pageSize, Integer page) {
            Page<LexSysDictData> lexSysDictDataPage = new Page<>(page, pageSize);
            QueryWrapper<LexSysDictData> queryWrapper = new QueryWrapper<>();
            if (query.getDictType() != null) {
                queryWrapper.eq("dict_type", query.getDictType());
            }
            if (query.getDictLabel() != null) {
                queryWrapper.like("dict_label", query.getDictLabel());
            }
            if (query.getStatus() != null) {
                queryWrapper.eq("status", query.getStatus());
            }
            List<LexSysDictData> lexSysDictDataList = lexSysDictDataMapper.selectList(lexSysDictDataPage, queryWrapper);
            long total = lexSysDictDataPage.getTotal();
            HashMap<String, Object> map = new HashMap<>();
            map.put("total", total);
            map.put("items", lexSysDictDataList);
            return CommonResult.success(map);
    }

    /**
     * 新增字典数据
     * @param dictData
     * @return
     */
    @Override
    public CommonResult createData(LexSysDictData dictData) {
        String creatBy = MyContext.getCurrentUserName();
        dictData.setCreateBy(creatBy);
        long now_time = System.currentTimeMillis();
        Timestamp timestamp = new Timestamp(now_time);
        dictData.setCreateTime(timestamp);
        int result = lexSysDictDataMapper.insert(dictData);
        return result > 0 ? CommonResult.success("新增数据成功！") : CommonResult.failed("新增数据失败！");
    }

    /**
     * 修改字典数据
     *
     * @param dictData
     * @return
     */
    @Override
    public CommonResult updateData(LexSysDictData dictData) {
        String update_by = MyContext.getCurrentUserName();
        dictData.setUpdateBy(update_by);
        long now_time = System.currentTimeMillis();
        Timestamp timestamp = new Timestamp(now_time);
        dictData.setUpdateTime(timestamp);
        int result = lexSysDictDataMapper.update(
                dictData,
                new QueryWrapper<LexSysDictData>()
                        .eq("dict_code", dictData.getDictCode()));
        return result > 0 ? CommonResult.success("修改数据成功！") : CommonResult.failed("修改数据失败！");
    }

    /**
     * 删除字典数据
     * @param dict_code
     * @return
     */
    @Override
    public CommonResult deleteData(Long dict_code) {
        int result = lexSysDictDataMapper.delete(
                new QueryWrapper<LexSysDictData>()
                        .eq("dict_code", dict_code));
        return result > 0 ? CommonResult.success("删除数据成功！") : CommonResult.failed("删除数据失败！");
    }

    /**
     * 更新数据字典状态
     * @param dictDataStatusQuery
     * @return
     */
    @Override
    public CommonResult updateDataStatus(DictDataStatusQuery dictDataStatusQuery) {
        LexSysDictData lexSysDictData = lexSysDictDataMapper.selectOne(
                new QueryWrapper<LexSysDictData>()
                        .eq("dict_code", dictDataStatusQuery.getDictCode()));
        if (lexSysDictData == null) {
            return CommonResult.failed("字典数据不存在！");
        }
        lexSysDictData.setStatus(dictDataStatusQuery.getStatus());
        int result = lexSysDictDataMapper.update(
                lexSysDictData,
                new QueryWrapper<LexSysDictData>()
                        .eq("dict_code", dictDataStatusQuery.getDictCode()));
        return result > 0 ? CommonResult.success("更新数据成功！") : CommonResult.failed("更新数据失败！");
    }

    /**
     * 根据字典类型获取字典数据
     * @param dictType
     * @return
     */
    @Override
    public CommonResult getDictDataByType(String dictType) {
        List<LexSysDictData> lexSysDictDataList = lexSysDictDataMapper.selectList(
                new QueryWrapper<LexSysDictData>()
                        .eq("dict_type", dictType).eq("status", 1));
        if (lexSysDictDataList != null) {
            return CommonResult.success(lexSysDictDataList);
        }
        return CommonResult.success(null);
    }
}
